package com.ny.service.impl;

import com.ny.entity.User;
import com.ny.mapper.UserMapper;
import com.ny.service.EmailService;
import com.ny.service.UserService;
import com.ny.until.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private EmailService emailService;
    @Override
    public int addUser(User user) {

        String pwd = user.getPassword();
        PasswordUtil.encryptPassword(pwd);
        user.setPassword(pwd);
        return userMapper.addUser(user);
    }

    @Override
    public User findUser(String username, String password) {
//        String pwd = PasswordUtil.encryptPassword(password);
        return userMapper.findUser(username,password);
    }
    @Override
    public User findUserByEmail(String email) {
        return userMapper.findUserByEmail(email);
    }

    @Override
    public int updatePassword(String password, String email) {
        // 密码加密
//        String pwd = PasswordUtil.encryptPassword(password);
        return userMapper.updatePassword(password,email);
    }

    // 给发件人发送验证码
    @Override
    public void sendToEmail(String toEmail) {
        // 执行发送验证码的逻辑
        emailService.sendEmail(toEmail,emailService.getCode());
        // 把验证码存储起来Redis中。
    }

    @Autowired
    private RedisTemplate<String, String> redisTemplate;
    @Override
    public boolean checkCode(String toEmail, String code) {
        // 获取Redis中存储的验证码
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        String redisCode = ops.get(toEmail);
        // 判断验证码是否一致
        return redisCode.equals(code);
    }

    @Override
    public User findByUsernameAndPassword(String username, String password) {
        // 实际项目中需加密密码比对（如 BCrypt）
        return userMapper.findByUsernameAndPassword(username, password);
    }


}
